package com.dokimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.dokimall.common.constant.ProductConstant;
import com.dokimall.common.to.SkuHasStockVo;
import com.dokimall.common.to.SkuReductionTo;
import com.dokimall.common.to.SpuBoundTo;
import com.dokimall.common.to.es.SkuEsModel;
import com.dokimall.common.utils.R;
import com.dokimall.product.entity.*;
import com.dokimall.product.feign.CouponFeignService;
import com.dokimall.product.feign.SearchFeignService;
import com.dokimall.product.feign.WareFeignService;
import com.dokimall.product.service.*;
import com.dokimall.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dokimall.common.utils.PageUtils;
import com.dokimall.common.utils.Query;

import com.dokimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuVo) {

        // 1 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseInfo(spuInfoEntity);

        // 2 保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        List<String> decript = spuVo.getDecript();
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(descEntity);

        // 3 保存spu的图片集 pms_spu_images
        List<String> images = spuVo.getImages();
        spuImagesService.setImagesInfo(spuInfoEntity.getId(), images);

        // 4 保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveInfo(productAttrValueEntities);

        // 5 保存spu的基本信息 dokimall_sms -> sms_spu_bounds（需要跨表）
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(spuVo.getBounds(),spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }

        // 6 保存当前spu对应的所有sku信息
        // 1)sku的基本信息 pms_sku_info

        List<Skus> skus = spuVo.getSkus();
        if (!skus.isEmpty()) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                //    private String skuName;
                //    private BigDecimal price;
                //    private String skuTitle;
                //    private String skuSubtitle;
                //  skus有的值，没有的需要set
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L); // 默认0件
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);
                // 2)sku的图片信息 pms_sku_images

                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setSkuId(skuId);
                    return skuImagesEntity;
                }).filter(entity->{
                    return StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                // 3)sku的销售属性 pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = item.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
//                    attrValueEntity.setAttrId(attr.getAttrId());
//                    attrValueEntity.setAttrName(attr.getAttrName());
//                    attrValueEntity.setAttrValue(attr.getAttrValue());
                    BeanUtils.copyProperties(attr,attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 4)sku的优惠、满减等信息 dokimall_sms ->sms_sku_ladder\sms_sku_full_reduction\sms_member_price\
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()>0 && skuReductionTo.getReducePrice().compareTo(new BigDecimal("0"))==1) {
                    R r1 = couponFeignService.saveSkuReductionInfo(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠/满减信息失败");
                    }
                }
            });
        }

    }

    @Override
    public PageUtils listSpuInfo(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String brandId = (String)params.get("brandId");
        if(StringUtils.isNotEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String catelogId = (String)params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }

        String status = (String)params.get("status");
        if(StringUtils.isNotEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }

        String key = (String)params.get("key");
        if (StringUtils.isNotEmpty(key)){
            queryWrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void spuUpById(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.listBySpuId(spuId);
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO 3、查出当前spuid对应的所有sku信息，品牌的名字
        List<ProductAttrValueEntity> valueEntities = productAttrValueService.listForSpu(spuId);
        List<Long> attrIds = valueEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        List<Long> attrCanSearchIds = attrService.getCanSearchAttrs(attrIds);
        Set<Long> attrSet = new HashSet<>(attrCanSearchIds);
        List<SkuEsModel.Attr> attrs = valueEntities.stream().filter(item -> {
            return attrSet.contains(item.getAttrId());
        }).map(attrValue -> {
            SkuEsModel.Attr skuattr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(attrValue, skuattr);
            return skuattr;
        }).collect(Collectors.toList());

        //TODO 1、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try{
            R skuHasStockVos = wareFeignService.hasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>(){
            };
            stockMap = skuHasStockVos.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("查询库存出现异常");
        }
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map((item) -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(item, skuEsModel);
            /** 需要另外赋值：price、skuImg、saleCount、hasStock、hotScore、brandName、brandImg、catalogName、attrs
             * private Long attrId;
             *         private String attrName;
             *         private String attrValue;*/
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());
            skuEsModel.setSaleCount(0L);
            // 查找库存
            //skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            // 设置库存信息
            if (finalStockMap == null) {
                // 远程服务出现问题，任然设置为null
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            }
            //TODO 2、热度评分，目前默认为0
            skuEsModel.setHotScore(0L);
            skuEsModel.setAttrs(attrs);
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setCatalogName(categoryService.getById(item.getCatalogId()).getName());
            return skuEsModel;
        }).collect(Collectors.toList());

        // TODO 4、数据发送给ES进行保存
        R r = searchFeignService.productStatusUp(collect);
        if(r.getCode()==0){
            // 远程调用成功，修改当前spu的状态
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(ProductConstant.StatusEnum.SUP_UP.getCode());
            spuInfoEntity.setUpdateTime(new Date());
            this.updateById(spuInfoEntity);
        }else {
            // 远程调用失败
            // TODO 重复调用？接口幂等性
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        // 先根据skuId查出SpuId
        SkuInfoEntity skuInfoEntity = skuInfoService.getOne(new QueryWrapper<SkuInfoEntity>().eq("sku_id", skuId));
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = this.getOne(new QueryWrapper<SpuInfoEntity>().eq("id", spuId));
        return spuInfoEntity;
    }

    private void saveBaseInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

}